<?php

namespace partner\functions\wechat\lib;

use Exception;
use WeChatPay\Crypto\Rsa;

class BaseWechatPartner
{
    private $separator = '_';

    // 要脱敏的属性
    protected $desensitization_properties = [];

    // 要上传到微信服务器的属性
    protected $upload_properties = [];

    public function __construct($params = [], $rsa)
    {
        foreach ($params as $property => $value) {
            if (property_exists($this, $property)) {
                $method = $this->getMethodNameByProperty($property);

                // 需要脱敏的属性
                if ($this->desensitization_properties && in_array($property, $this->desensitization_properties)) {
                    $value = $this->desensitizationProperties($rsa, $value);
                }

                // 需要上传多个文件时, 判断数量是否合法
                if (isset($this->upload_properties[$property])) {
                    // 上传多个文件的时候value是个数组
                    if (is_array($value) && count($value) > $this->upload_properties[$property])
                        throw new Exception("{$property}超过长度限制{$this->upload_properties[$property]}");                        
                }

                if (method_exists($this, $method)) {
                    $this->$method($value);
                }
            }            
        }        
    }

    public function getMethodNameByProperty(string $property_name)
    {
        $uncamelized_words = $this->separator. str_replace($this->separator, " ", strtolower($property_name));
        $camelized_words = ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $this->separator);
        return "set" . ucwords($camelized_words);
    }

    public function desensitizationProperties($rsa, $property)
    {
        return "把{$property}脱敏了";
    }
}